import axios from 'axios';
import store from '@/vuex/store'
import router from '@/router'
import { Toast } from 'mint-ui'
//api接口路径  （prod 线上-----advance 预发布 -----dev 本地）
let API_BASE_URL
switch (process.env.NODE_ENV) {
    case 'prod' :
        API_BASE_URL = 'https://biplus.dafyjk.net/biplus/app/'
        break 
    case 'advance' :
        API_BASE_URL = 'https://bisit.dafyjk.net/biplus/app/'
        break 
    case 'uat' :
        API_BASE_URL = 'https://biuat.dafyjk.net/biplus/app/'
        break 
    case 'dev' :
        API_BASE_URL = 'http://bisit.dafyjk.net/biplus/app/'
        break    
}

// http request 拦截器
axios.interceptors.request.use(
    config => {
        return config
    }, function (error) {
        return Promise.reject(error)
    }
)

// http response 拦截器
axios.interceptors.response.use(function (response) {
    // token 已过期，重定向到登录页面
    if (response.data.code == 401) {
        // store.dispatch('loginOut')
        // router.replace('/login')
    }
    return response
}, function (error) {
    return Promise.reject(error)
})

const axiosCreate = (type, path, data) => {
    let instance = axios.create({
        headers: {
            'Authorization': process.env.NODE_ENV !== 'dev' ? '' : '35777bc1-35e3-4efc-9026-3d779b9cece0'
        }
    })
    instance.defaults.withCredentials = true
    // 设置cookie
    if (type === 'get') {
      return instance({
        method: type,
        url: API_BASE_URL + path,
        params: data
      })
    } else if (type === 'post') {
        return instance({
            method: type,
            url: API_BASE_URL + path,
            data: data
        })
    }
}

export const http = (type, path, data) => {
    return new Promise((resolve, reject) => {
        store.commit('isLoader', false)
        axiosCreate(type, path, data).then(res => {
            let _data = res.data
            let _result = _data.data || {}
            // 请求接口成功
            if (_data.code == 10000) {
                if(_result.createTime && !store.getters.update && path.match('major')) {
                    store.commit('update', _result.createTime)
                }

                resolve(_result, _data)
            }
            // 账号已过期
            else if (_data.code == 30001) {
                console.log(res.data.msg)
            }
            else {
                console.log(path+'---'+res.data.msg)
            }
            store.commit('isLoader', true)
        }).catch(res => {
            console.log('发送的响应无效')
        });

    })
}
